//
//  SportViewController.m
//  CoolTennisBall
//
//  Created by 谢伟康 on 15/12/14.
//  Copyright © 2015年 CoolLang. All rights reserved.
//

#import "SportViewController.h"
#import "CommunicationManager.h"
#import "DeleteDate.h"
#import "FirmwareService.h"
#import "MBProgressHUD+HudTools.h"
#import "MenuViewController.h"
#import "NSDate+CM_DateTools.h"
#import "NSDate+FormateString.h"
#import "SearchViewController.h"
#import "SportHistoryRecordViewController.h"
#import "SportReportContainerViewController.h"
#import "SportSwingTableViewCell.h"
#import "SportTargetViewController.h"
#import "SportTipsTableViewCell.h"
#import "TargetProgressView.h"
#import "Triangle.h"
#import "WeekHandleItem.h"
#import <MJRefresh/MJRefresh.h>
#import <DateTools/DateTools.h>
#import "TennisSetWebViewController.h"
#import "NSBundle+CurrentLanguage.h"
#import "WarmTipsViewController.h"
#import "MenuTableViewController.h"
#import "iVersion.h"
#import "LGBluetooth.h"
#import "SportSectionHeaderView.h"
#import "SportSwingCell.h"
#import "SportRecordGroup.h"



static NSString * const kSportReportSegue = @"SportReportSegue";

NSString * const SportViewControllerShouldRefreshNotification = @"SportViewControllerShouldRefreshNotification";
NSString *const SportViewControllerDeleteTodayDataNotification = @"SportViewControllerDeleteTodayDataNotification";
NSString *const SportViewControllerUpdateSportDataNotification = @"SportViewControllerUpdateSportDataNotification";

@interface SportViewController ()<UITableViewDataSource,UITableViewDelegate,TargerProgressViewDelegate,SearchViewControllerDelegate>
@property (strong, nonatomic) IBOutlet TargetProgressView *targetView;//目标界面
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) BOOL isLinkStateImage;//是否连接
@property (assign, nonatomic) NSInteger indexOfNeedDetailSportRecordItem;//需要从蓝牙获取详情数据的索引，默认为0
@property (strong, nonatomic) NSArray * needDetailSportRecordItemArray;//需要从蓝牙获取详情数据的字典数组
@property (strong, nonatomic) RLMResults *sportRecordItemList;//经过降序处理的本地sportRecordItem数组

/** 按月份分组后的数据 */
@property (nonatomic, strong) NSMutableArray *sportRecordDataGroups;


@property (strong, nonatomic) RLMResults *sportRecords;//这周的运动记录
@property (strong, nonatomic) NSMutableArray *weekHandleItems;
@property (strong, nonatomic) NSString *hasSettingTargetSwing;//已设置的运动目标
@property (strong, nonatomic) NSString *averageTargetSwing;//平均的目标挥拍数
@property (strong, nonatomic) NSString *recommendTargetSwing;//推荐的挥拍数

@property (weak, nonatomic) IBOutlet UILabel *weekTotalSwingsDescriptionLabel;
@property (weak, nonatomic) IBOutlet UILabel *timesUnitLabel;
@property (weak, nonatomic) IBOutlet UIButton *sportTargetButton;
@property (nonatomic, strong) NSMutableArray *separateUploadApis;

@end

@implementation SportViewController
{
    SearchViewController *_searchViewController;
    NSTimer *_linkStateTimer;
    __block BOOL _isShowingMainPage;    // 是否在当前界面
    __block BOOL _checkNewFirmwareVersion;
    BOOL _isTransferSportDetailData;
    BOOL _shouldRefreshSportData;
}


#pragma mark - ViewLifeCircle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureLocalization];
    [self configureNav];
    [self configureSportRecordItemList];
    [self configureTargetView];
    [self registerNotification];
    
    [self configureTableView];
    [self addRefreshControl];
    
    __weak SportViewController *weakSelf = self;
    [self firstUploadSportDataWithFirstUploadBlock:^{
        [weakSelf synchronData];
    }];
    
    [self configureSportTargetWithTargetSwings:nil];
    
    [[iVersion sharedInstance] checkForNewVersion];
    
    self.view.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
    self.tableView.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configureLineState];
    _isShowingMainPage = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (_shouldRefreshSportData) {
        _shouldRefreshSportData = NO;
        if ([CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
            [self.tableView.mj_header beginRefreshing];
        }
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_linkStateTimer invalidate];
    _isShowingMainPage = NO;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

#pragma mark - 数据处理


#pragma mark - Localization
- (void)configureLocalization
{
    self.weekTotalSwingsDescriptionLabel.text = NSLocalizedString(@"This week you completed", nil);
    [self.sportTargetButton setTitle:NSLocalizedString(@"Target", nil) forState:UIControlStateNormal];
    self.timesUnitLabel.text = NSLocalizedString(@"Sport.Unit.Shots", nil);
    
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:kSportReportSegue]) {
        SportReportContainerViewController *sportReportContainerVC = segue.destinationViewController;
        SportRecordItem *item = (SportRecordItem *)sender;
        sportReportContainerVC.dateString = [item yearAndMonthAndDay];
        sportReportContainerVC.selectedDayTimeStamp = item.dateTimeStamp;
        sportReportContainerVC.recordItem = item;
    }
}

#pragma mark - Nav
- (void)configureNav
{
    self.navigationItem.title = NSLocalizedString(@"Sport.Statistics", nil);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Sport.History", nil) style:UIBarButtonItemStylePlain target:self action:@selector(openRecord)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"sport_icon_device"] style:UIBarButtonItemStylePlain target:self action:@selector(openMenu)];
}

- (void)openRecord{
    UIStoryboard *recordSb = [UIStoryboard storyboardWithName:@"Record" bundle:nil];
    SportHistoryRecordViewController *recordVC = [recordSb instantiateViewControllerWithIdentifier:@"SportHistoryRecordViewController"];
    NSLog(@"打开历史界面");
    [self.navigationController pushViewController:recordVC animated:YES];
}

//打开菜单
- (void)openMenu
{
    NSLog(@"打开菜单");
    if (![CommunicationManager shareInstance].isCentralReady) {
        return;
    }
    
    if (![CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
        [self showSearchDevicesView];
    }else{
        if (_isTransferSportDetailData) {
            [self showSynchronizeDeviceDataAlertView];
        } else {
            UIStoryboard *menuSb = [UIStoryboard storyboardWithName:@"Menu" bundle:nil];
            MenuViewController *menuVC = [menuSb instantiateViewControllerWithIdentifier:@"MenuViewController"];
            [menuVC presentInParentViewController:self.tabBarController animationType:DetailViewControllerPresentAnimationTypeFadeUp];
        }
    }
}

- (void)showSynchronizeDeviceDataAlertView
{
    FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Reading data now，Please wait", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
    [alertView customizeAppearance];
    [alertView show];
}

#pragma mark - RegisterNotification
- (void)registerNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePeripheralDisconnect:) name:kLGPeripheralDidDisconnect object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handlePeripheralConnect:) name:kLGPeripheralDidConnect object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleBluetoothStatePoweredOff:) name:kLGCentralManagerStatePoweredOffNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceNameChange:) name:kMenuChangeDeviceNameNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRefreshSportData) name:SportViewControllerShouldRefreshNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteTodayData) name:SportViewControllerDeleteTodayDataNotification object:nil];
}

- (void)handlePeripheralConnect:(NSNotification *)notification
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"sport_icon_device_linked"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(openMenu)];
    [self configureLineState];
    
}

- (void)handlePeripheralDisconnect:(NSNotification *)notification
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"sport_icon_device"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(openMenu)];
    [self configureLineState];
    [self recoverPeripheral];
    if (self.tableView.mj_header.isRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
}

- (void)handleBluetoothStatePoweredOff:(NSNotification *)notification
{
    [self configureLineState];
    if (self.tableView.mj_header.isRefreshing) {
        [self.tableView.mj_header endRefreshing];
    }
}

- (void)handleDeviceNameChange:(NSNotification *)notification
{
    NSString *deviceName = notification.userInfo[@"DeviceName"];
    self.navigationItem.title = deviceName;
}

- (void)handleRefreshSportData
{
    _shouldRefreshSportData = YES;
}


- (void)deleteTodayData {
    
    if (self.sportRecordItemList.count > 0 && [[self.sportRecordItemList[0] yearAndMonthAndDay] isEqualToString:[[NSDate date] formateYearMonthDay]]) {
        [self deleteDataWithSportRecord:self.sportRecordItemList[0] completeed:nil];
    }
    
    [self recoverPeripheral];
}

#pragma mark - 数据处理


#pragma mark - 网络同步请求
// 请求是否同步
- (void)synchronData
{
    [YFStatisticsApi getUseruploadSportDataLastTimeWithComplete:^(BOOL success, NSString *lastTimeStamp) {
        if (success) {
            User * user = [User getLastUser];
            NSLog(@"%@",lastTimeStamp);
            if ([user.lastUploadTime longLongValue] < [lastTimeStamp longLongValue]) {
                [YFStatisticsApi getMainHomeSportDatasWithUploadTime:user.lastUploadTime withComplete:^(BOOL success, YFStatisticsApi *resultApi, NSString *lastUploadTime, NSArray<SportRecordItem *> *sportRecordItemsList) {
                    if (success) {
                        // 将同步的数据判断后储存本地
                        [user addSportRecordItemsObject:sportRecordItemsList hasUpLoad:YES];
                        RLMRealm *realm = [RLMRealm defaultRealm];
                        [realm beginWriteTransaction];
                        user.lastUploadTime = lastUploadTime;
                        [realm commitWriteTransaction];
                        [self getSportRecordDeleteList];
                    }else {
                        NSLog(@"%@",resultApi.error);
                    }
                }];
            } else {
                [self getSportRecordDeleteList];
            }
        }
    }];
}

#pragma mark - 获取删除数据列表

- (void)getSportRecordDeleteList
{
    [YFStatisticsApi getHomeDeleteListWithComlpete:^(BOOL success, NSArray<DeleteDate *> *deleteSportDates) {
        if (success) {
            NSLog(@"'delete result': %@", deleteSportDates);
            User *user = [User getLastUser];
            [[RLMRealm defaultRealm] beginWriteTransaction];
            
            for (SportRecordItem *item in user.sportRecordItems) {
                item.shouldShield = NO;
            }
            [deleteSportDates enumerateObjectsUsingBlock:^(DeleteDate *obj, NSUInteger idx, BOOL *stop) {
                SportRecordItem *sportRecord = [[user.sportRecordItems objectsWhere:@"dateTimeStamp == %lld", [obj.unixTimeStamp longLongValue]] lastObject];
                if (sportRecord != nil) {
                    sportRecord.shouldShield = YES;
                }
            }];
            [[RLMRealm defaultRealm] commitWriteTransaction];
            [self configureSportRecordItemList];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
       
    }];
}

#pragma mark - 数据上传请求
- (void)uploadSportData
{
    User *user = [User getLastUser];
    RLMResults *recordResult = [user.sportRecordItems objectsWhere:@"hasUploadSportSessionValues == NO"];
    NSMutableArray * array = [NSMutableArray array];
    
    for (SportRecordItem *item in recordResult) {
        if (!item.hasUploadSportSessionValues && item.barChartItems.count > 0) {
            [array addObject:item];
        }
    }
    if (array.count == 0) {
        NSLog(@"无需要上传的数据");
        if (_checkNewFirmwareVersion) {
            [[FirmwareService sharedInstance] performRequestFirmwave:FirmwareAlertTypeHomePage beginUpdateFirmwareBlock:nil checkVersionCompletionBlock:^{
                _checkNewFirmwareVersion = NO;
            }];
        }
        return;
    }
    
    // 先清空需要上传的数据数组
    if ([self.separateUploadApis count] > 0) {
        [self.separateUploadApis removeAllObjects];
    }
    
    for (SportRecordItem *recordItem in array) {
        YFStatisticsApi *uploadApi = [YFStatisticsApi uploadHomeSportDataWithSportItems:@[recordItem]];
        [self.separateUploadApis addObject:uploadApi];
        
        [[YFNetworkingService sharedInstance] sendRequest:uploadApi callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                [self synchronizeSportDetailReportItem:recordItem complete:^(BOOL success) {
                    [[RLMRealm defaultRealm] beginWriteTransaction];
                    if (recordItem.barChartItems.count != 0) {
                        recordItem.hasUploadSportSessionValues = YES;
                    }
                    [[RLMRealm defaultRealm] commitWriteTransaction];
                    [self.separateUploadApis removeObject:uploadApi];
                    
                    if ([self.separateUploadApis count] == 0) {
                        [user configureLastUploadTimeStamp:[[result responseInfo] objectForKey:@"LastUploadTime"]];
                        [self configureSportRecordItemList];
                        
                        [self.tableView reloadData];
                        if (_checkNewFirmwareVersion) {
                            [[FirmwareService sharedInstance] performRequestFirmwave:FirmwareAlertTypeHomePage beginUpdateFirmwareBlock:nil checkVersionCompletionBlock:^{
                                _checkNewFirmwareVersion = NO;
                            }];
                        }
                    }
                    
                }];
            }else {
                [self.tableView reloadData];
                NSLog(@"失败");
            }
        }];
    }
}

#pragma mark 上传完成之后立即获取详情数据并同步
- (void)synchronizeSportDetailReportItem:(SportRecordItem *)item complete:(void(^)(BOOL success))completed {
    
    YFStatisticsApi *getSportDetailApi = [YFStatisticsApi getSportDetailReportWithSportDateString:[item yearAndMonthAndDay]];
    
    [[YFNetworkingService sharedInstance] sendRequest:getSportDetailApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            NSString *responseInfoJosnStr = [NSString dictionaryToJson:[result responseInfo]];
            // 转成json字符串
            [[RLMRealm defaultRealm] beginWriteTransaction];
            if (responseInfoJosnStr != nil) {
                item.detailReportInfo = responseInfoJosnStr;
                item.isSyncDetailReportData = YES;
                item.reportDetailLnaguage = [NSBundle currentLangeuage];
            }
            [[RLMRealm defaultRealm] commitWriteTransaction];
            if (completed) {
                completed(YES);
            }
        }else {
            if (completed) {
                completed(NO);
            }
        }
    }];
}

- (void)firstUploadSportDataWithFirstUploadBlock:(FirstUploadBlock)block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        User *user = [User getLastUser];
        RLMResults *recordResult = [user.sportRecordItems objectsWhere:@"hasUploadSportSessionValues == NO"];
        NSMutableArray * array = [NSMutableArray array];
        for (SportRecordItem *item in recordResult) {
            if (item.barChartItems.count != 0) {
                [array addObject:item];
            }
        }
        if (array.count == 0) {
            NSLog(@"无需要上传的数据");
            [self synchronData];
            return;
        }
        YFStatisticsApi *homeUploadApi = [YFStatisticsApi uploadHomeSportDataWithSportItems:array];
        [[YFNetworkingService sharedInstance] sendRequest:homeUploadApi callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                NSLog(@"上传成功");
                if (recordResult.count > 0) {
                    for (SportRecordItem *item in recordResult) {
                        RLMRealm *realm = [RLMRealm defaultRealm];
                        [realm beginWriteTransaction];
                        if (item.barChartItems.count != 0) {
                            item.hasUploadSportSessionValues = YES;
                        }
                        [realm commitWriteTransaction];
                    }
                }
            }
            block();
        }];
    });
    
}

#pragma mark - 蓝牙获取数据
//主界面数据
- (void)getMainSportItem
{
    _isTransferSportDetailData = NO;
    if (![CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Please Connect the Device", nil) inView:self.view];
        [self.tableView.mj_header endRefreshing];
        return;
    }
    
    [[CommunicationManager shareInstance] performOperationType:OperationTypeReadHomePageData object:nil completionBlock:^(BOOL success, id feedbackData ) {
        if (success) {
            [BTHandler handleHomePageData:feedbackData withCompletion:^(BOOL success, NSArray *sportRecordItems) {
                User *user = [User getLastUser];
                [user addSportRecordItemsObject:sportRecordItems hasUpLoad:NO];
                [self configureSportRecordItemList];
                [self.tableView reloadData];
                [self.tableView.mj_header endRefreshing];
                //后台获取动作详情数组
                [self configureNeedDetailDataReady:sportRecordItems];
                [self getDetailData];
                //刷新目标运动栏
                [self configureSportTargetWithTargetSwings:self.hasSettingTargetSwing];
                // 数据一个新，通知个人中心页面更新数据
                [[NSNotificationCenter defaultCenter] postNotificationName:SportViewControllerUpdateSportDataNotification object:nil];
            }];
            
        }else{
            [self.tableView.mj_header endRefreshing];
        }
    }];
    
    
}

//本地若有储存UUID就尝试30秒内自动连接
- (void)tryToConnect
{
    if (![CommunicationManager shareInstance].shouldRetryConnect) {
        return;
    }
    
    User *user = [User getLastUser];
    if (![user.userDevice.deviceUUID isEqualToString:@""]) {
        [[CommunicationManager shareInstance] connectWithoutRetryConnectPeripheralUUID:user.userDevice.deviceUUID completion:^(BOOL successful) {
            if (successful) {
                if (_isShowingMainPage) {
                    [self configureTimeStampSetting];
                    [self.tableView.mj_header beginRefreshing];
                }
            }
        }];
    }
}

- (void)recoverPeripheral
{
    if ([LGCentralManager sharedInstance].isCentralReady) {
        
        User *user = [User getLastUser];
        NSString *UUIDString = user.userDevice.deviceUUID;
        
        [[CommunicationManager shareInstance] recoverPeripheralWithUUIDString:UUIDString completionBlock:^(BOOL success) {
            if (success) {
                if (_isShowingMainPage) {
                    [self configureTimeStampSetting];
                    [self.tableView.mj_header beginRefreshing];
                }
            } else {
                NSLog(@"连接失败，重新尝试重连");
                [self recoverPeripheral];
            }
        }];
    }
}


// 获取动作详情数据
- (void)getDetailData
{
    if (![CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
        NSLog(@"蓝牙断开，无法获取动作详情数据");
        _isTransferSportDetailData = NO;
        return;
    }
    
    NSDictionary * paramDic = [self getNeedDetailSportRecordItemDayAndSwings];
    
    self.indexOfNeedDetailSportRecordItem++;
    if (paramDic == nil || paramDic.count <= 0) {
        [self uploadSportData];
        [self.tableView reloadData];
        _isTransferSportDetailData = NO;
        return;
    }
    
    _isTransferSportDetailData = YES;
    User *user = [User getLastUser];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"dateTimeStamp == %lld",[paramDic[@"SportRecordItem.UnixTimeStamp"] longLongValue]];
    
    RLMResults *recordResult = [user.sportRecordItems objectsWithPredicate:pred];
    SportRecordItem *item = [recordResult firstObject];
    
    NSIndexPath *indexPath = [self indexPathWithSportRecordItem:item];
    
    NSLog(@"%@--%lld",indexPath,[paramDic[@"SportRecordItem.UnixTimeStamp"] longLongValue]);
    
    NSInteger remainingSynSportDetailCount = [item amountOfCount] - [item.barChartItems count];
    
    NSMutableArray *calculateItems = [@[] mutableCopy];
    
    [[RLMRealm defaultRealm] beginWriteTransaction];
    item.hasUploadSportSessionValues = NO;
    item.hasReadItem = NO;
    [[RLMRealm defaultRealm] commitWriteTransaction];
    
    [[CommunicationManager shareInstance] performOperationType:OperationTypeReadSportDetailData object:paramDic completionBlock:^(BOOL success, id feedbackData) {
        if (success) {
            [BTHandler handleSportDetailData:feedbackData barChartItemBlock:^(BarChartItem *barChartItem) {
                SportSwingCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                //对应天数的item增加详情
                [calculateItems addObject:barChartItem];
                [cell configureWithItem:item indexDay:self.sportRecordItemList.count + 1 - indexPath.row isUploading:NO];
                
                CGFloat percent = [calculateItems count] * 1.0/remainingSynSportDetailCount;
                
                if (percent >= 1) {
                    cell.progressView.progress = 1.0;
                    cell.deatailLabel.text = NSLocalizedString(@"Cloud computing now...", nil);
                }else {
                    // NSLog(@"%f",percent);
                    cell.progressView.progress = percent;
                    cell.deatailLabel.text = [NSString stringWithFormat:NSLocalizedString(@"Reading data from device...%.0f%%", nil), percent * 100];
                }
                
            } completionBlock:^(BOOL successful) {
                
                [[RLMRealm defaultRealm] beginWriteTransaction];
                [item.barChartItems addObjects:calculateItems];
                [[RLMRealm defaultRealm] commitWriteTransaction];
                [self getDetailData];
            }];
        }
    }];
 
}


- (NSIndexPath *)indexPathWithSportRecordItem:(SportRecordItem *)sportRecordItem
{
    NSInteger section = 0;
    NSInteger row = 0;
    
    for (NSInteger i = 0; i < self.sportRecordDataGroups.count; i++) {
        SportRecordGroup *groupData = self.sportRecordDataGroups[i];
        
        for (NSInteger j = 0; j < groupData.sportRecordItems.count; j++) {
            SportRecordItem *sportItem = groupData.sportRecordItems[j];
            if(sportItem.dateTimeStamp == sportRecordItem.dateTimeStamp) {
                section = i;
                row = j;
                break;
            }
        }
    }
    
    NSIndexPath *indexPath = nil;
    if (section == 0) {
        indexPath = [NSIndexPath indexPathForRow:(row + 1) inSection:section];
    }else {
        indexPath = [NSIndexPath indexPathForRow:row inSection:section];
    }
    
    return indexPath;
}

//返回需要获取详情的天数及对应拍数day,item
- (NSDictionary *)getNeedDetailSportRecordItemDayAndSwings
{
    if (self.indexOfNeedDetailSportRecordItem < self.needDetailSportRecordItemArray.count) {
        return self.needDetailSportRecordItemArray[self.indexOfNeedDetailSportRecordItem];
    }else{
        return nil;
    }
}

//获取需要详情的参数数组
- (NSArray *)getNeedDetailSportRecordItemArray:(NSArray *)sportRecordItems
{
    NSMutableArray *arr = [NSMutableArray array];
    
//    NSMutableArray *dayArrM = [NSMutableArray array];
    
    NSMutableArray *arrM = [NSMutableArray array];
    [sportRecordItems enumerateObjectsUsingBlock:^(SportRecordItem *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [arrM addObject:[NSNumber numberWithLongLong:obj.dateTimeStamp]];
    }];
    
    for (SportRecordItem *item in self.sportRecordItemList) {
        if ([arrM containsObject:@(item.dateTimeStamp)] ) {
            NSLog(@"item%zd--%zd", item.barChartItems.count, [item amountOfCount]);
            if (item.barChartItems.count < [item amountOfCount]) {
                NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
                [dic setValue:[NSString stringWithFormat:@"%lld",item.dateTimeStamp] forKey:@"SportRecordItem.UnixTimeStamp"];
                [dic setValue:[NSString stringWithFormat:@"%d", (int)item.barChartItems.count] forKey:@"BarChartItem.Index"];
                [arr addObject:dic];
            }
        }
    }
    
    return arr;
}

//配置需要获取详情的参数
- (void)configureNeedDetailDataReady:(NSArray *)sportRecordItems
{
    self.indexOfNeedDetailSportRecordItem = 0;
    self.needDetailSportRecordItemArray = [self getNeedDetailSportRecordItemArray:(NSArray *)sportRecordItems];
}

//连接成功后设置左右手
- (void)configureHandStyle
{
    User *user = [User getLastUser];
    [[CommunicationManager shareInstance] performOperationType:OperationTypeHand object:[NSString stringWithFormat:@"%d", (int)user.userInforItem.hand] completionBlock:^(BOOL success, id feedbackData) {
        if (success) {
            [BTHandler handleHandData:feedbackData withCompletion:^(BOOL success, NSString *hand) {
                if (success) {
                    NSLog(@"设置左右手成功");
                }
            }];
        }
    }];
}

//设置时间戳校准
- (void)configureTimeStampSetting {
    [[CommunicationManager shareInstance] performOperationType:OperationTypeVerify object:nil completionBlock:^(BOOL success, id feedbackData) {
        if (success) {
            [BTHandler handleTimeStampVerifyData:feedbackData withCompletion:^(BOOL successful) {
                if (successful) {
                    NSLog(@"时间校正成功");
                    [self configureHandStyle];
                }
            }];
        }
    }];
}

#pragma mark - Private Method

- (void)configureSportTargetWithTargetSwings:(NSString *)targetSwings
{
    User *user = [User getLastUser];
    
    NSDate *endDate   = [NSDate date];
    NSDate *startDate = [NSDate formateString:@"2014-01-01 00:00:00"];
    long long endDateTimeStamp = [endDate unixTimeStamp];
    long long startDateTimeStamp = [startDate unixTimeStamp];
    
    self.sportRecords = [user.sportRecordItems objectsWhere:@"dateTimeStamp > %lld AND dateTimeStamp < %lld", startDateTimeStamp,endDateTimeStamp];
    self.sportRecords = [self.sportRecords sortedResultsUsingKeyPath:@"dateTimeStamp" ascending:YES];
    self.weekHandleItems = [NSMutableArray arrayWithArray:[self weekHandleItemsBySportRecordList:(NSArray *)self.sportRecords]];
    WeekHandleItem *lastWeekHandleItem = [self.weekHandleItems lastObject];
    
    if (targetSwings != nil) {
        [self.targetView configureTargetProgressViewWithWeekSwing:lastWeekHandleItem.amountSwingCount == nil ? @"0":lastWeekHandleItem.amountSwingCount targetSwings:targetSwings];
        return;
    }
    YFStatisticsApi *targetApi = [YFStatisticsApi getStatisticTarget];
    [[YFNetworkingService sharedInstance] sendRequest:targetApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            NSDictionary *responseDict = [result responseInfo];
            NSString *count = [responseDict objectForKey:@"Count"];
            NSString *avg = [responseDict objectForKey:@"Avg"];
            NSString *recommend = [responseDict objectForKey:@"Recommend"];
            
            [self.targetView configureTargetProgressViewWithWeekSwing:lastWeekHandleItem.amountSwingCount == nil ? @"0":lastWeekHandleItem.amountSwingCount targetSwings:count];
            self.hasSettingTargetSwing = count;
            self.averageTargetSwing = avg;
            self.recommendTargetSwing = recommend;
        }
    }];
    
}

#pragma mark - 周日期数据 -

- (NSArray *)weekHandleItemsBySportRecordList:(NSArray *)sportRecordItems
{
    NSMutableArray *weekItems = [@[] mutableCopy];
    WeekHandleItem *weekHandleItem = [[WeekHandleItem alloc] init];
    for (SportRecordItem *sportRecordItem in sportRecordItems) {
        
        if (sportRecordItem.shouldShield) {
            continue;
        }
        
        NSString *monday = [[sportRecordItem date] convertMonthDayByWeekDay:WeekDayMonday];
        NSString *sunday = [[sportRecordItem date] convertMonthDayByWeekDay:WeekDaySunday];
        NSString *startEndDateStr = [NSString stringWithFormat:@"%@-%@", monday, sunday];
        
        if ([weekHandleItem.startEndDateStr isEqualToString:startEndDateStr]) {
            [weekHandleItem addSportRecordItem:sportRecordItem];
        } else {
            weekHandleItem = [[WeekHandleItem alloc] init];
            [weekHandleItem addSportRecordItem:sportRecordItem];
        }
        
        if (![weekItems containsObject:weekHandleItem]) {
            
            [weekItems addObject:weekHandleItem];
        }
    }
    
    return [weekItems copy];
}

- (void)configureTableView
{
    [self.tableView registerNib:[UINib nibWithNibName:@"SportSwingTableViewCell" bundle:nil] forCellReuseIdentifier:@"SportSwingTableViewCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SportSwingCell" bundle:nil] forCellReuseIdentifier:@"SportSwingCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SportSectionHeaderView" bundle:nil] forHeaderFooterViewReuseIdentifier:@"SportSectionHeaderView"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SportTipsTableViewCell" bundle:nil] forCellReuseIdentifier:@"SportTipsTableViewCell"];
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    
}

- (void)addRefreshControl
{
    [self.tableView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
        [self getMainSportItem];
    }];
}

#pragma mark - 按时间戳降序排列每天的运动数据
- (void)configureSportRecordItemList
{
    User *user = [User getLastUser];

    self.sportRecordItemList = [user.sportRecordItems objectsWhere:@"shouldShield == NO"];
    
    [self.sportRecordItemList sortedResultsUsingKeyPath:@"dateTimeStamp" ascending:NO];
    // 按月份分组排序，月份从近到远
    [self configureSportRecordDataGroups];
    
}

- (void)configureSportRecordDataGroups {
    
    if (self.sportRecordItemList.count <= 0) {
        self.sportRecordDataGroups = nil;
        return;
    }
    
    SportRecordItem *temp = nil;
    NSMutableArray *tempArrm = [NSMutableArray array];
    
    NSMutableArray *arrM = [NSMutableArray array];
    self.sportRecordItemList = [self.sportRecordItemList objectsWhere:@"shouldShield == NO"];
    self.sportRecordItemList = [self.sportRecordItemList sortedResultsUsingKeyPath:@"dateTimeStamp" ascending:NO];
    for (SportRecordItem *item  in self.sportRecordItemList) {
        if ([item.date isToday]) {
            NSLog(@"%@",item);
        }
        if ([[item yearAndMonth] isEqualToString:[temp yearAndMonth]]) {
            [tempArrm addObject:item];
        }else if(![[item yearAndMonth] isEqualToString:[temp yearAndMonth]]) {
            
            temp = item;
            if (tempArrm.count > 0) {
                tempArrm = nil;
                tempArrm = [NSMutableArray array];
            }
            [tempArrm addObject:item];
            
            SportRecordGroup *groupModel = [[SportRecordGroup alloc] init];
            groupModel.sportRecordItems = tempArrm;
            groupModel.yearAndMonth = [temp yearAndMonth];
            
            [arrM addObject:groupModel];
        }
    }
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    
    [self.sportRecordDataGroups enumerateObjectsUsingBlock:^(SportRecordGroup *  _Nonnull groupModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [dictM setObject:groupModel forKey:[groupModel yearAndMonth]];
    }];
    
    [arrM enumerateObjectsUsingBlock:^(SportRecordGroup *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([dictM.allKeys containsObject:[obj yearAndMonth]]) {
            
            obj.isExpandGroup = [dictM[[obj yearAndMonth]] isExpandGroup];
        }else {
            if (idx == 0) {
                obj.isExpandGroup = YES;
            }else {
                obj.isExpandGroup = NO;
            }
        }
        
    }];
    
    self.sportRecordDataGroups = arrM;
   
}

- (void)configureTargetView
{
    self.targetView.delegate = self;
}

/**
 *  显示搜索设备
 */
- (void)showSearchDevicesView
{
    
    if (_searchViewController == nil || _searchViewController.parentViewController == nil) {
        
        [[CommunicationManager shareInstance] stopScanningPeripherals];
        
        SearchViewController *controller = [[SearchViewController alloc] initWithNibName:@"SearchViewController" bundle:nil];
        controller.delegate = self;
        
        [controller presentInParentViewController:self.tabBarController animationType:DetailViewControllerPresentAnimationTypeFade];
        _searchViewController = controller;
    }
    
}

//设置连接按钮显示状态
- (void)configureLineState
{
    if ([CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
        [_linkStateTimer invalidate];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"sport_icon_device_linked"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(openMenu)];
        self.navigationItem.title = [CommunicationManager shareInstance].lgPeripheral.name;
    }else{
        
        [_linkStateTimer invalidate];
        _isLinkStateImage = NO;
        _linkStateTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeLinkStateImage) userInfo:nil repeats:YES];
        self.navigationItem.title = NSLocalizedString(@"Sport.Statistics", nil);
    }
}

- (void)changeLinkStateImage
{
    NSString * imageName = _isLinkStateImage ? @"sport_icon_device_linked":@"sport_icon_device";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(openMenu)];
    _isLinkStateImage = !_isLinkStateImage;
}

- (void)deleteDataWithSportRecord:(SportRecordItem *)sportRecord completeed:(void(^)(BOOL success))completed {
    
    NSString *yMD = [sportRecord yearAndMonthAndDay];
    
    YFStatisticsApi *api = [YFStatisticsApi deleteHomeSportDatawithDateString:sportRecord.yearAndMonthAndDay flagReocrd:YES];
    
    [[YFNetworkingService sharedInstance] sendRequest:api callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            [[RLMRealm defaultRealm] beginWriteTransaction];
            if ([yMD isEqualToString:[[NSDate date] formateYearMonthDay]]) {
                [[RLMRealm defaultRealm] deleteObject:sportRecord];
                if ([CommunicationManager shareInstance].isPeripheralConnectedWithoutAlertView) {
                    [[CommunicationManager shareInstance] performOperationType:OperationTypeCleanData object:nil completionBlock:^(BOOL success, id feedbackData) {
                    }];
                }
            } else {
                sportRecord.shouldShield = YES;
            }
            [[RLMRealm defaultRealm] commitWriteTransaction];
            if (completed) {
                completed(YES);
            }
            
            [self configureSportRecordItemList];
            [self configureSportTargetWithTargetSwings:self.hasSettingTargetSwing];
            [self.tableView reloadData];
        } else {
            if (completed) {
                completed(NO);
            }
            
        }
    }];
    
}

- (void)showDeleteAlertViewAtIndexPath:(NSIndexPath *)indexPath
{

    SportRecordGroup *groupModel = self.sportRecordDataGroups[indexPath.section];
    
    SportRecordItem *sportRecord = nil;
    
    if (indexPath.section == 0) {
        if (indexPath.section == 0 && indexPath.row == 1) {
            sportRecord = self.sportRecordItemList[indexPath.row - 1];
        }else {
            sportRecord = groupModel.sportRecordItems[indexPath.row - 1];
        }
    }else {
        sportRecord = groupModel.sportRecordItems[indexPath.row];
    }
    
    NSString *tips = nil;
    if (indexPath.row == 1) {
        tips = NSLocalizedString(@"Confirm to delete today's sports data?", nil);
    } else {
        
        tips = [NSString stringWithFormat:NSLocalizedString(@"Confirm to delete sports data for %@?", nil), sportRecord.yearAndMonthAndDay];
    }
    
    FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:tips message:nil delegate:nil cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Yes", nil), nil];
    [alertView customizeAppearance];
    [alertView show];
    
//    NSString *yMD = [sportRecord yearAndMonthAndDay];
   
    __weak typeof(self) weakSelf = self;
    
    alertView.onOkAction = ^{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.tabBarController.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.label.font = [UIFont fontWithName:@"HelveticaNeue" size:18.0f];
        hud.label.textColor = [UIColor blackColor];
        hud.bezelView.color = [UIColor whiteColor];
        hud.dimBackground = YES;
        
        hud.label.text = NSLocalizedString(@"Deleting......", nil);
        
        [self deleteDataWithSportRecord:sportRecord completeed:^(BOOL success) {
            if (success) {
                hud.label.text = NSLocalizedString(@"Delete Successfully", nil);
                hud.label.textColor = kSelectedColor;
                [hud hideAnimated:YES afterDelay:1.0f];
                
                // 更新个人中心页面数据
                 [[NSNotificationCenter defaultCenter] postNotificationName:SportViewControllerUpdateSportDataNotification object:nil];
            }else {
                hud.label.text = NSLocalizedString(@"Poor network, Try again later", nil);
                [hud hideAnimated:YES afterDelay:1.0f];
                weakSelf.tableView.editing = NO;
            }
        }];
        
        
    };
    
    alertView.onCancelAction = ^{
        weakSelf.tableView.editing = NO;
    };
}

- (void)showWarmTips
{
    WarmTipsViewController *controller = [[UIStoryboard storyboardWithName:@"Sport" bundle:nil] instantiateViewControllerWithIdentifier:@"WarmTipsViewController"];
    controller.dismissBlock = ^{
        [self configureTimeStampSetting];
        [self.tableView.mj_header beginRefreshing];
    };
    [controller presentInParentViewController:self.tabBarController];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.sportRecordDataGroups.count == 0 ? 1 : self.sportRecordDataGroups.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SportRecordGroup *groupModel = nil;
    if (self.sportRecordDataGroups.count > 0) {
        groupModel = self.sportRecordDataGroups[section];
    }
    
    if (section == 0) {
        return self.sportRecordDataGroups.count == 0 ? 2:groupModel.sportRecordItems.count + 1;
    }else {
        if (groupModel.isExpandGroup) {
            return groupModel.sportRecordItems.count;
        }else {
            return 0;
        }
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SportRecordGroup *groupModel = nil;
    if (self.sportRecordDataGroups.count > 0) {
        groupModel = self.sportRecordDataGroups[indexPath.section];
    }
    
    if (indexPath.row == 0 && indexPath.section == 0) {
        SportSwingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SportSwingTableViewCell"];
        
        SportRecordItem *item = [groupModel.sportRecordItems firstObject];
        [cell configureBarHeightWithSportRecordItem:item];
        return cell;
    }else if (indexPath.row == 1 && indexPath.section == 0 && self.sportRecordDataGroups.count == 0){
        SportTipsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SportTipsTableViewCell"];
        return cell;
        
    }else {
        SportSwingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SportSwingCell"];
        SportRecordItem *item = nil;
        if (indexPath.section == 0) {
            item = groupModel.sportRecordItems[indexPath.row - 1];
        }else {
            item = groupModel.sportRecordItems[indexPath.row];
        }
        BOOL isUploading = [self.separateUploadApis count] > 0;
        
        NSUInteger indexDay = [self.sportRecordItemList indexOfObject:item];
        
        [cell configureWithItem:item indexDay:(self.sportRecordItemList.count - indexDay) isUploading:isUploading];
        
        if (self.sportRecordDataGroups.count == 0 && indexPath.row == 1 && indexPath.section == 0) {
            [cell showlineView:NO];
        }else {
            [cell showlineView:YES];
        }
        return cell;
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    SportRecordGroup *groupModel = nil;
    if (self.sportRecordDataGroups.count > 0) {
        groupModel = self.sportRecordDataGroups[indexPath.section];
    }
    
    if (indexPath.section == 0) {
        if (indexPath.row > 0 && [groupModel.sportRecordItems count] > 0) {
            return !_isTransferSportDetailData;
        }
    }else {
        if ([groupModel.sportRecordItems count] > 0) {
            return !_isTransferSportDetailData;
        }
    }
    
    return NO;
}


- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    __weak typeof(self) weakSelf = self;

    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:NSLocalizedString(@"Delete", nil) handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [weakSelf showDeleteAlertViewAtIndexPath:indexPath];
    }];
    deleteAction.backgroundColor =  [UIColor colorWithHex:0xf3f3f3];
    if (@available(iOS 11.0, *)) {
        deleteAction.backgroundColor = [UIColor redColor];
    }
    return @[deleteAction];
}

#pragma mark - UITableView Delegate
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    
    view.tintColor = [UIColor whiteColor];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return nil;
    }else {
        SportRecordGroup *groupModel = self.sportRecordDataGroups[section];
        
        SportSectionHeaderView *sectionHeaderView = [SportSectionHeaderView sportSectionHeaderView];
        sectionHeaderView.groupModel = groupModel;
        sectionHeaderView.backgroundColor = [UIColor colorWithHex:0xf3f3f3];
        __weak typeof(self) weakSelf = self;
        
        [sectionHeaderView setReloadSectionCell:^{
            [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationFade];
        }];
        return sectionHeaderView;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return 0.1;
    }else {
        SportRecordGroup *groupModel = self.sportRecordDataGroups[section];
        return groupModel.headViewHeight;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 217 + 10;
        } else if (self.sportRecordDataGroups.count == 0) {
            return [NSBundle currentLangeuage] == kLanguageFrennch ? 170:160;
        }else if(self.sportRecordDataGroups.count > 0 && indexPath.row == 1){
            return 70;
        }else {
            return 88;
        }
    }else {
        return 88;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        return;
    } else if (indexPath.section == 0 && indexPath.row == 1 && self.sportRecordDataGroups.count == 0) {
        
        return;
    }
    SportRecordGroup *groupModel = self.sportRecordDataGroups[indexPath.section];
    
    SportRecordItem *item = nil;
    if (indexPath.section == 0) {
        item = groupModel.sportRecordItems[indexPath.row - 1];
    }else {
        item = groupModel.sportRecordItems[indexPath.row];
    }
    
    if (!item.hasUploadSportSessionValues) {
        return;
    }
    
    [[RLMRealm defaultRealm] beginWriteTransaction];
    item.hasReadItem = YES;
    [[RLMRealm defaultRealm] commitWriteTransaction];
    
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    
    [self performSegueWithIdentifier:kSportReportSegue sender:item];
}

#pragma mark - TargerProgressViewDelegate

- (void)openSportTargetView
{
    SportTargetViewController *targetVC = [[SportTargetViewController alloc] init];
    targetVC.hasSettingTargetSwings = [self.hasSettingTargetSwing integerValue];
    targetVC.averageTargetSwings = [self.averageTargetSwing integerValue];
    targetVC.recommendTargetSwings = [self.recommendTargetSwing integerValue];
    targetVC.targetCompleBlock = ^(NSInteger targetSwings){
        self.hasSettingTargetSwing = [NSString stringWithFormat:@"%ld",(long)targetSwings];
        [self configureSportTargetWithTargetSwings:self.hasSettingTargetSwing];
    };
    targetVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:targetVC animated:YES];
}

#pragma mark - SearchViewControllerDelegate
- (void)searchViewControllerDidConnectPeripheral:(SearchViewController *)controller
{
    _checkNewFirmwareVersion = YES;
    [self configureLineState];
    
    if ([CommunicationManager shareInstance].isDFUMode) {
        [[FirmwareService sharedInstance] performRequestFirmwave:FirmwareAlertTypeHomePage beginUpdateFirmwareBlock:nil checkVersionCompletionBlock:^{
            _checkNewFirmwareVersion = NO;
        }];
    } else {
        User *user = [User getLastUser];
        if ([user.sportRecordItems count] == 0) {
            [self showWarmTips];
        } else {
            [self configureTimeStampSetting];
            [self.tableView.mj_header beginRefreshing];
        }
    }
}

#pragma mark - Getter/Setter

- (NSMutableArray *)separateUploadApis
{
    if (_separateUploadApis == nil) {
        _separateUploadApis = [NSMutableArray array];
    }
    
    return _separateUploadApis;
}

- (NSMutableArray *)sportRecordDataGroups {
    if (_sportRecordDataGroups == nil) {
        _sportRecordDataGroups = [NSMutableArray array];
    }
    return _sportRecordDataGroups;
}


@end
